package manager


import db.Order
import ext.log
import org.json.JSONArray
import org.json.JSONObject


object ReportManager : Runnable {

    private fun toJson(orderInfos: ArrayList<Order>): String {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        val arr = JSONArray()
        orderInfos.forEach { arr.put(it.toJsonWithOrder()) }
        json.put("arr", arr)
        return json.toString()
    }

    fun tryUpdate() = AsyncTask.post(this)

    private fun updateOrderToServer() {

        val orderInfos = Order.withDatabase()
        if (orderInfos.isEmpty()) {
            log("没有订单需要提交")
            return
        }
        val content = toJson(orderInfos)
        log(content, "提交出货信息")
        val ret = NetworkManager.reportWithServer(content)
        log("---$ret", "提交返回")
        for (order in orderInfos) {
            order.delete()
        }
    }

    override fun run() {

        try {
            updateOrderToServer()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

